<template>
  <div class="ele-body">
    <a-row :gutter="12">
      <a-col :style="{ width: width300 ? '300px' : '400px' }">
        <org-tree @treeSelect="treeSelect" ref="orgTreeRef" @changeWidth="changeWidth"></org-tree>
      </a-col>
      <a-col :style="{ width: width300 ? 'calc(100% - 300px)' : 'calc(100% - 400px)' }">
        <div class="ten-height bg-white padding10 box-shadow">
          <div class="table-header">
            <div class="header-left">
              <a-space size="large">
                <a-input v-model:value="where.searchText" placeholder="姓名、账号（回车搜索）" @pressEnter="reload"
                         class="search-input">
                  <template #suffix>
                    <search-outlined @click="reload"/>
                  </template>
                </a-input>
                <drop-down :list="statusList" defaultName="状态" ref="statusRef" keyValue="id" keyName="name"
                           @dropClick="statusChange"/>
                <a-button type="primary" style="background-color: red; border-color: red" class="border-radius"
                          @click="clear"
                >清空条件
                </a-button
                >
              </a-space>
            </div>
            <div class="header-right">
              <a-space>
                <a-button type="primary" class="border-radius" @click="openAddEdit()" v-permission="['ADD_USER']"
                >
                  <plus-outlined/>
                  新建
                </a-button
                >
                <a-dropdown>
                  <template #overlay>
                    <a-menu @click="moreClick">
                      <a-menu-item key="1">
                        <ordered-list-outlined/>
                        自定义列
                      </a-menu-item>
                      <div v-permission="['DELETE_USER']">
                        <a-menu-item key="2">
                          <delete-outlined style="color: red"/>
                          删除
                        </a-menu-item>
                      </div>
                    </a-menu>
                  </template>
                  <a-button>
                    更多
                    <small-dash-outlined/>
                  </a-button>
                </a-dropdown>
              </a-space>
            </div>
          </div>
          <div class="table-content">
            <common-table
              :columns="columns"
              :where="where"
              bordered
              rowId="userId"
              ref="tableRef"
              url="/sysUser/page"
              :scroll="{ x: 'max-content', y: 'calc(100vh - 240px)' }"
            >
              <template #bodyCell="{ column, record }">
                <!-- 姓名 -->
                <template v-if="column.dataIndex == 'realName'">
                  <a @click="detail(record)">{{ record.realName }}</a>
                </template>
                <!-- 公司 -->
                <template v-if="column.dataIndex == 'company'">
                  {{ record?.userOrgDTO?.companyName ? record?.userOrgDTO?.companyName : '' }}
                </template>
                <!-- 部门 -->
                <template v-if="column.dataIndex == 'dept'">
                  {{ record?.userOrgDTO?.deptName ? record?.userOrgDTO?.deptName : '' }}
                </template>
                <!-- 职务 -->
                <template v-if="column.dataIndex == 'positionName'">
                  {{ record?.userOrgDTO?.positionName ? record?.userOrgDTO?.positionName : '' }}
                </template>
                <!-- 性别 -->
                <template v-if="column.dataIndex == 'sex'">
                  <span v-if="record.sex == 'M'">男</span>
                  <span v-if="record.sex == 'F'">女</span>
                </template>
                <!-- 状态 -->
                <template v-if="column.dataIndex == 'statusFlag'">
                  <vxe-switch
                    v-model="record.statusFlag"
                    :open-value="1"
                    :close-value="2"
                    @change="statusFlagChange(record)"
                    :disabled="disabled"
                  ></vxe-switch>
                </template>
                <!-- 操作 -->
                <template v-if="column.key == 'action'">
                  <a-space>
                    <icon-font
                      type="class"
                      iconClass="icon-button-edit"
                      color="var(--primary-color)"
                      font-size="20px"
                      fontWeight="bold"
                      title="编辑"
                      v-permission="['EDIT_USER']"
                      @click="openOtherAddEdit(record)"
                    ></icon-font>
<!--                    <icon-font
                      type="class"
                      iconClass="icon-button-edit"
                      color="var(&#45;&#45;primary-color)"
                      font-size="20px"
                      fontWeight="bold"
                      title="编辑"
                      v-permission="['EDIT_USER']"
                      @click="openAddEdit(record)"
                    ></icon-font>-->
                    <icon-font
                      type="class"
                      iconClass="icon-button-delete"
                      color="red"
                      font-size="20px"
                      fontWeight="bold"
                      title="删除"
                      v-permission="['DELETE_USER']"
                      @click="remove(record)"
                    ></icon-font>
                    <icon-font
                      type="class"
                      iconClass="icon-button-assign-role"
                      color="var(--primary-color)"
                      font-size="20px"
                      fontWeight="bold"
                      title="分配角色"
                      v-permission="['ASSIGN_USER_ROLE']"
                      @click="roleClick(record)"
                    ></icon-font>
                    <icon-font
                      type="class"
                      iconClass="icon-button-reset-password"
                      color="var(--primary-color)"
                      font-size="20px"
                      fontWeight="bold"
                      title="重置密码"
                      v-permission="['RESET_PASSWORD']"
                      @click="resetPassword(record)"
                    ></icon-font>
                  </a-space>
                </template>
              </template>
            </common-table>
          </div>
        </div>
      </a-col>
    </a-row>

    <!-- 自定义列 -->
    <Custom
      v-model:visible="isShowCustom"
      v-if="isShowCustom"
      :data="columns"
      @done="val => (columns = val)"
      :fieldBusinessCode="fieldBusinessCode"
    />

    <!-- 新增编辑弹框 -->
    <UserAddEdit v-model:visible="showEdit" v-if="showEdit" :data="current" @done="reload"/>

    <userOtherDetail v-model:visible="showOtherEdit" v-if="showOtherEdit" :data="current" @done="reload"/>
    <!-- 查看详情抽屉 -->
    <UserDetail v-model:visible="showDetail" v-if="showDetail" :data="current"/>
    <!-- 分配角色 -->
    <AllocationRole v-model:visible="showRole" v-if="showRole" :data="current" @done="reload"/>
  </div>
</template>

<script setup name="BackEndUser">
import OrgTree from './org-tree.vue';
import {UsersApi} from './api/UsersApi';
import {useUserStore} from '@/store/modules/user';
import {ref, createVNode, onMounted, computed} from 'vue';
import {message, Modal} from 'ant-design-vue/es';
import UserDetail from './components/user-detail.vue';
import userOtherDetail from './components/user-other-detail.vue';
import UserAddEdit from './components/user-add-edit.vue';
import AllocationRole from './components/allocation-role.vue';
import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
import {CustomApi} from '@/components/common/Custom/api/CustomApi';

// 状态列表
const statusList = ref([
  {
    id: '',
    name: '全部状态'
  },
  {
    id: 1,
    name: '启用'
  },
  {
    id: 2,
    name: '禁用'
  }
]);
// 表格配置
const columns = ref([
  {
    key: 'index',
    title: '序号',
    width: 48,
    align: 'center',
    isShow: true,
    hideInSetting: true,
    customRender: ({index}) => tableRef.value.tableIndex + index
  },
  {
    dataIndex: 'realName',
    title: '姓名',
    align: 'center',
    ellipsis: true,
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'account',
    title: '账号',
    width: 100,
    ellipsis: true,
    align: 'center',
    isShow: true
  },
  {
    dataIndex: 'employeeNumber',
    title: '工号',
    width: 100,
    ellipsis: true,
    align: 'center',
    isShow: true
  },
  {
    dataIndex: 'company',
    title: '主要公司',
    align: 'center',
    ellipsis: true,
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'dept',
    title: '主要部门',
    align: 'center',
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'positionName',
    title: '职务',
    align: 'center',
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'sex',
    title: '性别',
    align: 'center',
    width: 100,
    isShow: true
  },
  {
    dataIndex: 'statusFlag',
    title: '状态',
    width: 100,
    align: 'center',
    isShow: true
  },
  {
    dataIndex: 'createTime',
    title: '创建时间',
    align: 'center',
    width: 150,
    isShow: true
  },
  {
    key: 'action',
    title: '操作',
    align: 'center',
    width: 200,
    isShow: true
  }
]);
// ref
const tableRef = ref(null);
const statusRef = ref(null);
const orgTreeRef = ref(null);
// 宽度是否300
const width300 = ref(true);
const userStore = useUserStore();

// 搜索条件
const where = ref({
  orgIdCondition: '',
  statusFlag: '',
  searchText: ''
});
// 是否显示自定义列
const isShowCustom = ref(false);
// 当前行数据
const current = ref(null);
// 是否显示新增编辑弹框
const showEdit = ref(false);
const showOtherEdit = ref(false);
// 是否显示详情抽屉
const showDetail = ref(false);
// 是否显示分配角色弹框
const showRole = ref(false);
// 业务标识的编码
const fieldBusinessCode = ref('USER_TABLE');
// 是否禁用
const disabled = computed(() => {
  if (userStore.authorities.find(item => item == 'UPDATE_USER_STATUS')) {
    return false;
  }
  return true;
});

onMounted(() => {
  getColumnData();
});

// 获取表格配置
const getColumnData = () => {
  CustomApi.getUserConfig({fieldBusinessCode: fieldBusinessCode.value}).then(res => {
    if (res.tableWidthJson) {
      columns.value = JSON.parse(res.tableWidthJson);
    }
  });
};

// 左侧树选中
const treeSelect = (selectedKeys, metadata) => {
  where.value.orgIdCondition = selectedKeys[0];
  reload();
};

// 更多点击
const moreClick = ({key}) => {
  if (key == '1') {
    isShowCustom.value = true;
  } else if (key == '2') {
    batchDelete();
  }
};

// 点击搜索
const reload = () => {
  tableRef.value.reload();
};

// 清除搜索条件
const clear = () => {
  where.value.searchText = '';
  where.value.statusFlag = '';
  where.value.orgIdCondition = '';
  orgTreeRef.value.currentSelectKeys = [];
  statusRef.value.changeDropname('状态');
  reload();
};

// 状态改变
const statusChange = val => {
  where.value.statusFlag = val;
  reload();
};

// 新增编辑点击
const openAddEdit = record => {
  current.value = record;
  showEdit.value = true;
};

const openOtherAddEdit = record => {
  current.value = record;
  showOtherEdit.value = true;
};
// 查看详情
const detail = record => {
  current.value = record;
  showDetail.value = true;
};

// 删除单个
const remove = record => {
  Modal.confirm({
    title: '提示',
    content: '确定要删除选中的用户吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: async () => {
      const res = await UsersApi.delete({userId: record.userId});
      message.success(res.message);
      reload();
    }
  });
};

// 批量删除
const batchDelete = () => {
  if (tableRef.value.selectedRowList && tableRef.value.selectedRowList.length == 0) {
    return message.warning('请选择需要删除的用户');
  }
  Modal.confirm({
    title: '提示',
    content: '确定要删除选中的用户吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: async () => {
      const res = await UsersApi.batchDelete({userIdList: tableRef.value.selectedRowList});
      message.success(res.message);
      reload();
    }
  });
};

// 点击分配角色
const roleClick = record => {
  current.value = record;
  showRole.value = true;
};

// 重置密码
const resetPassword = record => {
  Modal.confirm({
    title: '提示',
    content: '确定要重置此用户的密码为"123456"吗?',
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    onOk: async () => {
      let result = await UsersApi.resetPassword({userId: record.userId});
      message.success(result.message);
      reload();
    }
  });
};

// 切换人员状态
const statusFlagChange = record => {
  UsersApi.updateStatus({userId: record.userId, statusFlag: record.statusFlag}).then(res => {
    message.success(res.message);
  });
};

// 切换左侧树宽度
const changeWidth = val => {
  width300.value = val;
};
</script>

<style scoped lang="less">
.table-header {
  width: 100%;
  height: 40px;
  line-height: 40px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}

.table-content {
  width: 100%;
  height: calc(100% - 50px);
}

:deep(.ant-table-body) {
  min-height: calc(100vh - 240px) !important;
}

.search-input {
  width: 300px;
  border-radius: 5px;
}
</style>
